//
//  SubjectStoreEditViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/11/8.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "SubjectStoreEditViewController.h"
#import "SubjectUploadPicTableViewCell.h"
#import "SubjectNameTableViewCell.h"
#import "SubjectChildBtnTableViewCell.h"
#import "SubjectWriteTableViewCell.h"
#import "ChooseIsokTableViewCell.h"
#import "AlreadlyChangeTableViewCell.h"
#import "SubjectContentDetialModel.h"
#import "UILabel+NSAttributeString.h"
#import "EditSubjectModel.h"
#import "HelpViewController.h"
#import "WriteTextViewController.h"
@interface SubjectStoreEditViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)TB_TableView *homeTableiew;

@property(nonatomic,strong)SubjectContentDetialModel *detialModel;

@property(nonatomic,strong)UIButton *ScoreSureBtn;//检查员确认按钮

@end

@implementation SubjectStoreEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isScanphotos=YES;
    
    self.title=@"详情";
    
    [self loadDatas];
    // Do any additional setup after loading the view.
    
    [self addNavigationItemWithTitles:@[@"帮助"] isLeft:NO target:self action:@selector(helpClicked) tags:nil];
    
    [self addNavigationItemWithImageNames:@[@"返回白色"] Titles:@[@"返回"] isLeft:YES target:self action:@selector(backBtnClicked) tags:nil];
}

- (void)backBtnClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)helpClicked
{
    HelpViewController *Patro=[HelpViewController new];
    JobListModel *list=[JobListModel new];
    list.pageOn = YES;
    list.pageSize = 10;
    list.currentPage = 1;
    
    Patro.ishidenSearch = YES;
    Patro.Reqmodel = list;
    Patro.isEdit=NO;
    Patro.isdeleMore=NO;
    Patro.isGroupStyle=YES;
    
    [self.navigationController pushViewController:Patro animated:YES];
}


-(TB_TableView*)homeTableiew
{
    if (!_homeTableiew) {
        
        CGRect frame;
        
        if (kDevice_Is_iPhoneX) {
            
            frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-SCREEN_WIDTH/320.*45-IPhoneXTableHeight);
            
        }else{
            
            frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-SCREEN_WIDTH/320.*45);
            
        }
        
        _homeTableiew=[[TB_TableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        
        _homeTableiew.delegate=self;
        
        _homeTableiew.dataSource=self;
        
        _homeTableiew.estimatedRowHeight=60;
        
        _homeTableiew.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        
        _homeTableiew.tableFooterView=[[UIView alloc]init];
        
        [_homeTableiew registerNib:[UINib nibWithNibName:@"SubjectNameTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
        
        [_homeTableiew registerNib:[UINib nibWithNibName:@"SubjectChildBtnTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell2"];
        
        [_homeTableiew registerNib:[UINib nibWithNibName:@"SubjectWriteTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell3"];
        
        [_homeTableiew registerNib:[UINib nibWithNibName:@"ChooseIsokTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell4"];

        [_homeTableiew registerNib:[UINib nibWithNibName:@"AlreadlyChangeTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell6"];
        
        [_homeTableiew registerClass:[SubjectUploadPicTableViewCell class] forCellReuseIdentifier:@"PhotoCell"];
        
    }
    
    
    return _homeTableiew;
}


-(UIButton*)ScoreSureBtn
{
    if (!_ScoreSureBtn) {
        
        _ScoreSureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        
        if (kDevice_Is_iPhoneX) {
            _ScoreSureBtn.frame=CGRectMake(0, SCREEN_HEIGHT-50-64-IPhoneXTableHeight, SCREEN_WIDTH, SCREEN_WIDTH/320.*45);
            
        }else{
            
            _ScoreSureBtn.frame=CGRectMake(0, SCREEN_HEIGHT-50-64, SCREEN_WIDTH, SCREEN_WIDTH/320.*45);
        }
        
        _ScoreSureBtn.backgroundColor=TBColorProvideBtnbg;
        
        _ScoreSureBtn.titleLabel.font=[UIFont systemFontOfSize:18];
        
        [_ScoreSureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_ScoreSureBtn setTitle:@"提交" forState:UIControlStateNormal];
        
        [_ScoreSureBtn addTarget:self action:@selector(SureAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _ScoreSureBtn;
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *Api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/inspectDetail.json" andrequestTime:5 andParams:@{@"logId":[NSString stringWithFormat:@"%ld",self.logs.logId]} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [Api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        [self stopLoadingAnimation];
        
        self.detialModel=[SubjectContentDetialModel mj_objectWithKeyValues:responseObject];
        
        if (responseStatus==1) {
            //请求成功
            
             [self.view addSubview:self.homeTableiew];
            
            if (self.detialModel.data.state!=2) {
                
                
                 [self.view addSubview:self.ScoreSureBtn];
                
            }else{
                
                self.homeTableiew.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    
            }
      
            [self.homeTableiew reloadData];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
        
        
    }];
    
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 4;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section==0) {
        
        return self.detialModel.data.child.count+1;
        
    }else if (section==1)
    {
        
        return 1;
        
    }else if (section==2)
    {
        
        return 3;
        
    }else{
        
        return 2;
        
    }
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        
        if (indexPath.row==0) {
            
            SubjectNameTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
            
            if (self.detialModel.data.lev) {
                
                  cell.NameLabel.attributedText=[cell.NameLabel StartWithStr:[NSString stringWithFormat:@"%@☆",self.detialModel.data.name]];
                
            }else{
                
                cell.NameLabel.text=self.detialModel.data.name;
                
            }
            return cell;
            
        }else{
            
            ContentChild *child=self.detialModel.data.child[indexPath.row-1];
            
            if (child.isFill) {
                //可输入
                
                SubjectWriteTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
                
                cell.isEnableEdit=NO;
                
                cell.child=child;
                
                return cell;
                
            }else{
                //不可输入
                SubjectChildBtnTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
                
                cell.child=child;
                
                return cell;
                
            }
      
        }
        
        
    }else if (indexPath.section==1)
    {
        ChooseIsokTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell4" forIndexPath:indexPath];
        
        cell.isEnableEdit=NO;
        
        cell.isok=self.detialModel.data.isOk;
        
        return cell;
        
    }else if (indexPath.section==2)
    {
        
        if (indexPath.row==0||indexPath.row==2) {
            
            AlreadlyChangeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell6" forIndexPath:indexPath];
            
             cell.accessoryType=UITableViewCellAccessoryNone;
      
            if (indexPath.row==0) {
                
                cell.TipLabel.text=@"补充说明";
                
                if (self.detialModel.data.remark.length==0) {
                    
                    cell.ContentLabel.text=@"无";
                    
                }else{
                    
                    cell.ContentLabel.text=self.detialModel.data.remark;
                }
                
            }else{
                
                cell.TipLabel.text=@"整改建议";
                
                if (self.detialModel.data.advise.length==0) {
                    
                    cell.ContentLabel.text=@"无";
                    
                }else{
                    
                    cell.ContentLabel.text=self.detialModel.data.advise;
                }
                
            }
            
            return cell;
            
        }else{
            
            SubjectUploadPicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PhotoCell" forIndexPath:indexPath];
            cell.isEdit=NO;//是否可编辑
            cell.ImageArr=[HelpWay imageStrToArr:self.detialModel.data.remarkImg];//传递图片数组
            
            TBWeak;
            //浏览图片
            cell.ScanBlock=^(NSInteger num)
            {
                [weakSelf.ScanPhotoArr removeAllObjects];
                
                for (NSString*imagestr in [HelpWay imageStrToArr:self.detialModel.data.remarkImg]) {
                    
                    [weakSelf.ScanPhotoArr addObject:[MWPhoto photoWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",ReqUrl,imagestr]]]];
                    
                }
                
                [weakSelf GoToPhotoScanAndIndex:num];
                
            };
            
            return cell;
            
            
        }
        
    }else{
        
        if (indexPath.row==0) {
            
 
           AlreadlyChangeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell6" forIndexPath:indexPath];
      
            cell.TipLabel.text=@"整改说明";
                
            cell.ContentLabel.text=self.detialModel.data.reformRemark;
        
            if (self.detialModel.data.state==2&&self.detialModel.data.confirmState) {
                
                //通过审核了，不需要编辑
                 cell.accessoryType=UITableViewCellAccessoryNone;
        
            }else{
            
                cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
            
            }
                
            return cell;
            
        }else{
            
            SubjectUploadPicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PhotoCell" forIndexPath:indexPath];
            
            if (self.detialModel.data.state==2&&self.detialModel.data.confirmState) {

                cell.isEdit=NO;
                
            }else{
                cell.isEdit=YES;//是否可编辑
            }
            cell.ImageArr=[HelpWay imageStrToArr:self.detialModel.data.reformImage];//传递图片数组
            
            TBWeak;
            
            //删除图片
            cell.delePhoto=^(NSInteger num)
            {
                NSArray *arr=[HelpWay imageStrToArr:self.detialModel.data.reformImage];
                
                NSMutableArray *ReArr=[[NSMutableArray alloc]initWithArray:arr];
                
                [ReArr removeObjectAtIndex:num];
                
                NSString*FinalStr=@"";
                
                for (NSString*imageStr in ReArr) {
                    
                    if (FinalStr.length==0) {
                        
                        FinalStr=imageStr;
                    }else{
                        
                        
                        FinalStr=[NSString stringWithFormat:@"%@|%@",FinalStr,imageStr];
                    }
                    
                }
                
                self.detialModel.data.reformImage=FinalStr;
                
                [weakSelf.homeTableiew reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                
            };
            
            //浏览图片
            cell.ScanBlock=^(NSInteger num)
            {
                [weakSelf.ScanPhotoArr removeAllObjects];
                
                for (NSString*imagestr in [HelpWay imageStrToArr:self.detialModel.data.reformImage]) {
                    
                    [weakSelf.ScanPhotoArr addObject:[MWPhoto photoWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",ReqUrl,imagestr]]]];
                    
                }
                
                [weakSelf GoToPhotoScanAndIndex:num];
                
            };
            
            //上传图片
            cell.UploadBlock=^()
            {
                
                
                [weakSelf GotoLibaraySelectPhotoNum:9 andIsCantainScan:NO andBlock:^(NSString * armStr) {
                    
                    if (self.detialModel.data.reformImage.length==0) {
                        
                        self.detialModel.data.reformImage=armStr;
                        
                    }else{
                        
                        self.detialModel.data.reformImage=[NSString stringWithFormat:@"%@|%@",self.detialModel.data.reformImage,armStr];
                    }
                    
                    [weakSelf.homeTableiew reloadData];
                    
                }];
                
            };
            
            return cell;
            
        }
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==0) {
        return UITableViewAutomaticDimension;
        
    }else if (indexPath.section==1)
    {
        
        return 80;
        
    }else if (indexPath.section==2)
    {
        
        if (indexPath.row==0||indexPath.row==2) {
            
              return UITableViewAutomaticDimension;
            
        }else{
            
            NSArray *arr=[HelpWay imageStrToArr:self.detialModel.data.remarkImg];
            
            if (arr.count==0) {
                
                return 0;
                
            }else{
                
                NSInteger colorm=(arr.count-1)/3+1;//每行放三个，一个有多少行
                
                CGFloat cellHeight=(SCREEN_WIDTH-30-10*2)/3.0;
                
                return 15+10*(colorm-1)+colorm*cellHeight+21;
                
            }
       
        }
   
    }else{
        
        if (indexPath.row==0) {
            
            return UITableViewAutomaticDimension;
            
        }else{
            
            NSArray *arr=[HelpWay imageStrToArr:self.detialModel.data.reformImage];
            
             if (self.detialModel.data.state==2&&self.detialModel.data.confirmState) {
                
                 if (arr.count==0) {
                     
                     return 0;
                     
                 }else{
                 
                 NSInteger colorm=(arr.count-1)/3+1;//每行放三个，一个有多少行
                 
                 CGFloat cellHeight=(SCREEN_WIDTH-30-10*2)/3.0;
                 
                 return 15+10*(colorm-1)+colorm*cellHeight+21;
                 }
             }else{
     
                 NSInteger colorm=arr.count/3+1;//每行放三个，一个有多少行
            
                 CGFloat cellHeight=(SCREEN_WIDTH-30-10*2)/3.0;
            
                 return 15+10*(colorm-1)+colorm*cellHeight+21;
            
             }
        }
        
    }
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==3&&indexPath.row==0) {
        
        if (self.detialModel.data.state==2&&self.detialModel.data.confirmState) {
        
            return;
            
        }
        WriteTextViewController *write=[[WriteTextViewController alloc]initWithPloader:@"请输入内容" andTipName:@"整改说明" andOrinStr:self.detialModel.data.reformRemark andFinshBlock:^(NSString * arm) {
     
            self.detialModel.data.reformRemark=arm;
            
            [self.homeTableiew reloadData];
            
        }];
        
        self.modalPresentationStyle = UIModalPresentationCurrentContext;
        write.modalPresentationStyle = UIModalPresentationOverFullScreen;
        
        [self presentViewController:write animated:YES completion:^{
 
        }];
 
    }
    
    
    
}

#pragma mark-确认事件
-(void)SureAction:(UIButton*)sender
{
    EditSubjectModel *model=[EditSubjectModel new];
    
    
    model.reformRemark=self.detialModel.data.reformRemark;
    
    model.reformImage=self.detialModel.data.reformImage;
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/inspectEdit.json" andrequestTime:5 andParams:@{@"logId":[NSString stringWithFormat:@"%ld",self.logs.logId],@"type":@"1",@"postData":[HelpWay dictionaryToJSON:model.mj_keyValues]} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"提交成功"];
            
            _block();
            
              [self.navigationController popViewControllerAnimated:YES];
            
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 15;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.1;
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
